package com.springboot.fast.controller.front;

import com.springboot.fast.controller.util.BaiduWebImageOCRUtil;
import com.springboot.fast.model.bean.Question;
import com.springboot.fast.model.dto.Result;
import com.springboot.fast.model.service.IQuestionService;
import com.springboot.fast.model.util.AnsjSegUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/front/question")
public class FrontQuestionController {
    private static Logger log = LoggerFactory.getLogger(FrontQuestionController.class);
    @Autowired
    IQuestionService questionService;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String question() {
        return "front/question";
    }


    /**
     * 文字搜索
     * @param question
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public Result questionPost(@RequestBody Question question) {
        String title = question.getTitle();
        // 对问题进行分词
        List<String> words = AnsjSegUtil.parseStr(title);
        List<Question> questions = questionService.getQuestionList(title, words);
        return Result.success(questions);
//        return Result.success(getChatbot);
    }

    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String detail(long id, Model model) {
        Question question = questionService.getById(id);
        model.addAttribute("question", question);
        return "front/questionDetail";
    }

    @RequestMapping(value = "/img", method = RequestMethod.POST)
    @ResponseBody
    public Result questionImgPost(MultipartFile picFile) throws IOException {
        // 拿到传来的图片字节数据
        byte[] data = picFile.getBytes();
        JSONObject res = BaiduWebImageOCRUtil.OCRByte(data);
        JSONArray wordResult = res.optJSONArray("words_result");
        if (wordResult.length() == 0) {
            return Result.error("图片识别失败");
        }
        String resultSting = wordResult.getJSONObject(0).optString("words");

        log.info(res.toString() + ":" + resultSting);
        List<String> words = AnsjSegUtil.parseStr(resultSting);
        List<Question> questions = questionService.getQuestionList(resultSting, words);
        if (questions == null) {
            return Result.error("题库中不含有这个题目");
        }

        return Result.success(questions);
    }
}
